package org.testfire.realm.view.tags.agent;

import com.lookingglasssoftware.lgsrealm.LGSChecksum;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import org.apache.log4j.Logger;
import org.testfire.realm.control.agent.ResponseHandlers.TestsetResponseHandler;
import org.testfire.realm.control.auth.user.UserDBAO;
import org.testfire.realm.control.exception.UserNotFoundException;
import org.testfire.realm.control.testfire.TestFireDBAO;
import org.testfire.realm.model.entities.User;
import org.testfire.realm.util.UtilityBean;

/**
 * Created by IntelliJ IDEA.
 * User: granum
 * Date: Sep 3, 2007
 * Time: 8:50:49 PM
 */
public class AgentHandlerTag extends SimpleTagSupport
{

    Logger log = Logger.getLogger( AgentHandlerTag.class );

    private String task;

    public void doTag() throws JspException, IOException
    {
        super.doTag();

        ServletRequest request = ((PageContext)this.getJspContext()).getRequest();
        doAgentRequest( request );
    }

    public void doAgentRequest( ServletRequest request ) throws IOException
    {
        try
        {
            String userName = request.getParameter( "username" );
            String password = request.getParameter( "password" );
            User u = UserDBAO.getInstance().getUser( userName );
            String md5 = "";
            try
            {
                md5 = LGSChecksum.getHMAC_MD5( password, u.getName() + UtilityBean.SYSTEM_SALT );
            }
            catch ( Exception e )
            {
                log.error( "", e );
            }
            if ( !u.getMd5().equals( md5 ) )
            {
                throw new UserNotFoundException(  );
            }
            if ( task.equals( "testset_result" ) )
            {
                
                TestsetResponseHandler handler =
                    TestFireDBAO.getValueExpresionValue( TestsetResponseHandler.class );
                handler.perform( u, (HttpServletRequest)request );
            }

        }
        catch ( Exception e )
        {
            PrintWriter p = new PrintWriter( this.getJspContext().getOut() );
            log.error( "", e );
            e.printStackTrace( p );
            p.flush();
        }
        catch ( UserNotFoundException e )
        {
            PrintWriter p = new PrintWriter( this.getJspContext().getOut() );
            log.error( "", e );
            e.printStackTrace( p );
            p.flush();
        }

    }

    public String getTask()
    {
        return task;
    }

    public void setTask( String task )
    {
        this.task = task;
    }
}